package fimuni.pb138.repositar;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.stream.StreamResult;

import net.sf.saxon.Configuration;
import net.sf.saxon.query.DynamicQueryContext;
import net.sf.saxon.query.StaticQueryContext;
import net.sf.saxon.query.XQueryExpression;

public class XQueryProcessor {

	public static String processQuery(String query) {
		try {
			Configuration config = new Configuration();
			StaticQueryContext staticContext = config.newStaticQueryContext();
			XQueryExpression exp = staticContext.compileQuery(query);

			DynamicQueryContext dynamicContext = new DynamicQueryContext(config);

			Properties props = new Properties();
			props.setProperty(OutputKeys.METHOD, "html");
			// props.setProperty(OutputKeys.INDENT, "yes");

			final StringBuilder sb = new StringBuilder();
			OutputStream os = new OutputStream() {

				@Override
				public void write(int b) throws IOException {
					sb.append((char) b);
				}
			};
			exp.run(dynamicContext, new StreamResult(os), props);

			// System.out.println("sb = " + sb.toString());
			return sb.toString();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
